﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;


public static class GlobalExtensions
{
    public static bool IsNullOrEmpty(this string s) { return string.IsNullOrEmpty(s); }
    public static IEnumerable<T> Maybe<T>(this IEnumerable<T> source) { return source ?? Enumerable.Empty<T>(); }
    public static T Cast<T>(this object o) { return (T)o; }
    /// <summary>
    /// Returns the type of the contained enumerable if it is generic
    /// </summary>
    /// <param name="e"></param>
    /// <returns>null if type is not generic</returns>
    public static Type TryGetGenericType(this IEnumerable e)
    {
        IEnumerator ator = null;
        Type elementType = null;
        try
        {
            ator = e.GetEnumerator();
            var enumeratorType = ator.GetType();

            //get the type the enumerator contains
            elementType = enumeratorType.GetGenericArguments().Single();
        }
        finally
        {
            if (ator is IDisposable)
            {
                ator.Cast<IDisposable>().Dispose();
            }
        }
        return elementType;
    }
    public static T AsOrThrow<T>(this object o) where T:class 
    {
        var result = o as T;
        if (result==null)
            throw new InvalidCastException();

        return result;

    }

}
